package com.fc.test.util.wx;

import net.sf.json.JSONObject;

/**
 * @description 
 * @author liuhh
 * @date 2018-1-11
 */
public class WeiXinTokenThread implements Runnable{
	
	//获取access_token请求地址
	public static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	//获取jsapi_ticket请求地址
	public static String JSAPI_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
	// 第三方用户唯一凭证  
	public static String APP_ID = "wx0a1f4afa36726125";
	 // 第三方用户唯一凭证密钥  
	public static String SECRET = "5d43d737186d21424e4eda6c95312a67";
    public static String ACCESS_TOKEN = "";  
    public static String JSAPI_TICKET = "";  
  
    public void run() {  
        while (true) {  
            try {  
            	String tokenUrl = ACCESS_TOKEN_URL.replace("APPID", APP_ID).replace("APPSECRET", SECRET); 
        	    String jsonObjectToken = HttpUtils.sendGet(tokenUrl);  
        	    JSONObject jsonToken = JSONObject.fromObject(jsonObjectToken);  
        	    try {
        	    	ACCESS_TOKEN = (String)jsonToken.get("access_token");
        		} catch (Exception e) {
        			e.printStackTrace();
        		}
        	    
                if (!"".equals(ACCESS_TOKEN) && ACCESS_TOKEN!=null) {  
                    System.out.println("获取access_token 值 ：=============="+ ACCESS_TOKEN );  
                    //获取JSAPI_TICKET
                    String ticketUrl = JSAPI_TICKET_URL.replace("ACCESS_TOKEN", ACCESS_TOKEN); 
            	    String jsonObjectTicket = HttpUtils.sendGet(ticketUrl);  
            	    JSONObject jsonTicket = JSONObject.fromObject(jsonObjectTicket);  
            	    try {
            	    	JSAPI_TICKET = (String)jsonTicket.get("ticket");
            		} catch (Exception e) {
            			e.printStackTrace();
            		}
            		System.out.println("获取jsapi_ticket值：==============" + JSAPI_TICKET);
                    // 有效期 7200秒， 休眠7000秒  
                    Thread.sleep(7000 * 1000);  
                } else {  
                    // 如果access_token为null，60秒后再获取  
                    Thread.sleep(60 * 1000);  
                }  
            } catch (InterruptedException e) {  
                try {  
                    Thread.sleep(60 * 1000);  
                } catch (InterruptedException e1) {  
                	e.printStackTrace();
                }  
                e.printStackTrace();
            }  
        }  
    }  
}
